<template>

  <div class="login-wrap">
    <div class="ms-login">
      <div class="ms-title">论文管理系统</div>
      <div class="login-register">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <!--登录-->
          <el-tab-pane id="login" label="登录" name="first">
            <el-form :model="param" :rules="rules1" ref="login" label-width="0" class="ms-content">
              <el-form-item prop="username">
                <el-input v-model="param.username" placeholder="username">
                  <template #prepend>
                    <el-button :icon="User"></el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                    type="password"
                    placeholder="password"
                    v-model="param.password"
                    @keyup.enter="submitForm1(login)"
                    show-password
                >
                  <template #prepend>
                    <el-button :icon="Lock"></el-button>
                  </template>
                </el-input>
              </el-form-item>
              <div class="login-btn">
                <el-button type="primary" @click="submitForm1(login)">登录</el-button>
              </div>
              <!--
              <p class="login-tips">Tips : 用户名和密码随便填。</p>
              -->
            </el-form>
          </el-tab-pane>
          <!--注册-->
          <el-tab-pane label="注册" name="second">
            <el-form
                ref="ruleFormRef"
                :model="ruleForm"
                :rules="rules"
                label-width="120px"
                class="demo-form-inline"
                :size="formSize"
                status-icon
                style="max-width: 550px"

            >
              <!--用户名-->
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="ruleForm.email"/>
                <el-button v-if="!countDownIng" id="sendCode" type="primary" size="default" @click="sendCode"
                           style="position: absolute;left:102%;top: 0"
                >获取验证码</el-button>
                <span v-if="countDownIng" class="status">{{countDownTime}}</span>
              </el-form-item>

              <el-form-item label="验证码" prop="code">
                <el-input v-model="ruleForm.code" ></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password1">
                <el-input v-model="ruleForm.password1" type="password" show-password/>
              </el-form-item>
              <el-form-item label="重复密码" prop="password2">
                <el-input v-model="ruleForm.password2" type="password" show-password/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm1(ruleFormRef)"
                >提交</el-button
                >
                <el-button @click="resetForm1(ruleFormRef)">重置</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>

        </el-tabs>
      </div>


    </div>
  </div>






</template>

<script setup lang="ts">
import {ref,reactive, onMounted, toRefs} from 'vue';
import { useTagsStore } from '../store/tags';
import { usePermissStore } from '../store/permiss';
import { useRouter } from 'vue-router';
import { ElMessage,TabsPaneContext } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { Lock, User } from '@element-plus/icons-vue';
import {getEmailCode} from '../api/register';

//登录
interface LoginInfo {
  username: string;
  password: string;
}


const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
const router = useRouter();
const param = reactive<LoginInfo>({
  username: 'admin',
  password: '123123'
});

const rules1: FormRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};
const permiss = usePermissStore();
const login = ref<FormInstance>();
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const submitForm1 = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid: boolean) => {
    if (valid) {
      ElMessage.success('登录成功');
      localStorage.setItem('ms_username', param.username);
      const keys = permiss.defaultList[param.username == 'admin' ? 'admin' : 'user'];
      permiss.handleSet(keys);
      localStorage.setItem('ms_keys', JSON.stringify(keys));
      router.push('/');
    } else {
      ElMessage.error('登录失败');
      return false;
    }
  });
};
//注册
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  email:'',
  code:'',
  password1:'',
  password2:'',
})
const validatePass2 = (rule:any,value:any,callback:any)=>{
  if(value===''){
    return callback(new Error('请再次输入密码'))
  }
  else if(value!==ruleForm.password1){
    return callback(new Error('两次输入的密码不一致'))
  }
}
const validEmail = (rule:any,value:any,callback:any)=>{
  let emailReg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if(value===""||value===undefined||value==null){
    return callback(new Error('邮箱不能为空'));
  }
  setTimeout(()=>{
    if(emailReg.test(value)){
      callback();
    }else{
      callback(new Error('邮箱格式错误'));
    }
  },300);

}

const rules = reactive<FormRules>({
  email: [
    {required:true,validator:validEmail,trigger:'blur'}
  ],
  password1:[
    {required:true,message:'请输入密码',trigger:'blur'},
    { pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}$/,
      message: '密码必须同时包含字母、数字和特殊字符其中三项且8-20位' }
  ],
  password2:[
    {required:true,validator:validatePass2,trigger:'blur'}
  ],
  code:[
    {required:true,message:'请输入验证码',trigger:'blur'}
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('注册成功')
      router.push('#login')
    } else {
      console.log('注册失败', fields)
    }
  })
}

const resetForm1 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}



const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))


const tags = useTagsStore();
tags.clearTags();
</script>

<style scoped>
.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url(../assets/img/book.png);
  background-size: 100%;
}
.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #fff;
}
.ms-login {
  position: absolute;
  left: 38%;
  top: 30%;
  width: 50%;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.3);
  overflow: hidden;
}
.ms-content {
  padding: 30px 30px;
}
.login-btn {
  text-align: center;
}
.login-btn button {
  width: 50%;
  height: 36px;
  margin-bottom: 10px;
}
.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #fff;
}
.login-register{
  position: relative;
  width: 97%;
  left: 1.5%;
}
</style>
